package com.cms.manage.controller;

import com.alibaba.fastjson.JSON;
import com.cms.manage.common.SysCode;
import com.cms.manage.model.CmsUser;
import com.cms.manage.service.LoginService;
import com.cms.manage.util.*;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Api(description = "用户操作")
//@ApiIgnore()
@RestController     //等同于同时加上了@Controller和@ResponseBody
@RequestMapping("/cms/user")
public class LoginController extends BaseController{

      private static final Logger Log = LoggerFactory.getLogger(LoginController.class);
	  
	  @Autowired
	  private LoginService loginService;

	  @ApiOperation(value="用户注册", notes="用户注册")
		@ApiImplicitParams({
		@ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String",paramType = "form"),
		@ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String",paramType = "form"),
		@ApiImplicitParam(name = "headImg", value = "头像地址", required = false, dataType = "String",paramType = "form"),
		@ApiImplicitParam(name = "sex", value = "性别", required = false, dataType = "String",paramType = "form"),
		@ApiImplicitParam(name = "age", value = "年龄", required = false, dataType = "String",paramType = "form"),
		@ApiImplicitParam(name = "nikeName", value = "昵称", required = false, dataType = "String",paramType = "form"),	
		})
	    @RequestMapping(value = "/register",method = RequestMethod.POST)
	    @ResponseBody
	    public ResponseEntity<Map<String,Object>> register(HttpServletRequest request){		
			  Map<String,String> data =RequestMapToUtil.getPostByTextPlain(request);		   
	    	  Map<String, Object> result = new HashMap<String, Object>();
	    	  result = loginService.register(data);
	    	  System.out.println();
	    	if(result.get("code")==SysCode.error){
	    		return ResponseEntity.status(HttpStatus.OK).body(ERROR(result.get("message"),null));
	    	 }
	    	return ResponseEntity.status(HttpStatus.OK).body(SUCCESS(result.get("message"),null)); 
	    }
	  
	    @ApiOperation(value="激活用户", notes="激活用户")
		@ApiImplicitParams({
		@ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String",paramType = "form"),
		@ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String",paramType = "form"),
		@ApiImplicitParam(name = "cdkey", value = "秘钥", required = false, dataType = "String",paramType = "form"),
		})
	    @RequestMapping(value = "/activate",method = RequestMethod.POST)
	    @ResponseBody
	    public ResponseEntity<Map<String,Object>> activate (HttpServletRequest request){		
			  Map<String,String> data =RequestMapToUtil.getPostByTextPlain(request);			   
	    	  Map<String, Object> result = new HashMap<String, Object>();
	    	  result = loginService.activate(data);
	    	if(result.get("code")==SysCode.error){
	    		return ResponseEntity.status(HttpStatus.OK).body(ERROR(result.get("message"),null));
	    	 }
	    	return ResponseEntity.status(HttpStatus.OK).body(SUCCESS(result.get("message"),null)); 
	    }
	  
	  
	  @ApiOperation(value="用户登录", notes="登录")
		@ApiImplicitParams({
		@ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String",paramType = "form"),
		@ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String",paramType = "form"),
		})
	    @RequestMapping(value = "/login",method = RequestMethod.POST)
	    @ResponseBody
	    public ResponseEntity<Map<String,Object>> login(HttpServletRequest request,HttpServletResponse response){		
		  Map<String,String> data =RequestMapToUtil.getPostByTextPlain(request);					  
    	  Map<String, Object> result = new HashMap<String, Object>();
          String username = data.get("name");
          String password = data.get("password");
          //先检查cookie中的user对象
          String cmsUser4 = CookieUtil.getCookieValue(request, Constant.COKKIES_USER_ID);
          if (StringUtils.isBlank(cmsUser4) && StringUtils.isBlank(username) && StringUtils.isBlank(password)) {
              return ResponseEntity.status(HttpStatus.OK).body(NO_LOGIN());
          }   
          if(StringUtils.isNotBlank(cmsUser4)){//如果cookies 不为空
        	  String userJson4 ="";
        	  CmsUser user4;
    			try {
    				Claims  claims = JWTUtil.parseJWT(cmsUser4);
    				 //解密获得 userjson
    			     userJson4 = claims.getSubject();
    			     //获取登录信息
    			    user4 = JSON.parseObject(userJson4, CmsUser.class);	  
    		    	user4.setPassword("");	    	 
    	 	    	 //对session的用户信息进行加密处理
    		    	  Map<String, String> map = new HashMap<String, String>();
    		    	  String userJson5 = JSON.toJSONString(user4);	    	
    		          map.put("subject", userJson5);
    		          map.put("minutes", "360");//设置seesion有效期,6个小时
    		          String cmsUser3 ="";
    		          try {
    		        	  cmsUser3 = JWTUtil.createJWT(map);
    				} catch (ParseException e) {
    					return ResponseEntity.status(HttpStatus.OK).body(ERROR("系统异常,登陆失败！",null));
    				}	
    		          //通过cokkies信息重新设置session
    		    	SessionUtil.set(request, Constant.SESSION_USER, cmsUser3);
    	            SessionUtil.set(request, Constant.SESSION_USER_ID, user4.getId());
    	            SessionUtil.set(request, Constant.SESSION_NIKE_NAME, user4.getNikename());
    	              Map<String, Object> adminMap = new HashMap<>();
    	              adminMap.put("userId", user4.getId());
    	              adminMap.put("username", user4.getName());
    	              adminMap.put("nickname", user4.getNikename());
    	           return ResponseEntity.status(HttpStatus.OK).body(SUCCESS("登录成功", adminMap));
    			} catch (Exception e) {
    				 //异常表示jwt过期
                  if (StringUtils.isBlank(username) && StringUtils.isBlank(password)) {
                      return ResponseEntity.status(HttpStatus.OK).body(LONIN_TIMEOUT());
                  }				
    			}
          }        
          //验证用户名密码
          result = loginService.login(data);
    	  if(result.get("code")==SysCode.error){
	    		return ResponseEntity.status(HttpStatus.OK).body(ERROR(result.get("message"),null));
	     } else {
	    	  CmsUser user = (CmsUser) result.get("data"); 
	    	  user.setPassword("");	    	 
 	    	 //对session的用户信息进行加密处理
	    	  Map<String, String> map = new HashMap<String, String>();
	    	  String userJson = JSON.toJSONString(user);	    	
	          map.put("subject", userJson);
	          map.put("minutes", "360");//设置seesion有效期,6个小时
	          String cmsUser ="";
	          try {
	        	  cmsUser = JWTUtil.createJWT(map);
			} catch (ParseException e) {
				return ResponseEntity.status(HttpStatus.OK).body(ERROR("系统异常,登陆失败！",null));
			}	
	          //设置session
	    	  SessionUtil.set(request, Constant.SESSION_USER, cmsUser);
              SessionUtil.set(request, Constant.SESSION_USER_ID, user.getId());
              SessionUtil.set(request, Constant.SESSION_NIKE_NAME, user.getNikename());
             //设置cookis 
              Map<String, String> map2 = new HashMap<String, String>();   	
	    	  map2.put("subject", userJson);
	    	  map2.put("minutes", "7200");//设置cookies有效期,5天
	          String cmsUser2 ="";
	          try {
	        	  cmsUser2 = JWTUtil.createJWT(map);
			} catch (ParseException e) {
				return ResponseEntity.status(HttpStatus.OK).body(ERROR("系统异常,登陆失败！",null));
			}
              CookieUtil.setCookie(request, response, Constant.COKKIES_USER_ID, cmsUser2, 60 * 60 * 24 * 1);//1天
              Map<String, Object> adminMap = new HashMap<>();
              adminMap.put("userId", user.getId());
              adminMap.put("username", user.getName());
              adminMap.put("nickname", user.getNikename());
              return ResponseEntity.status(HttpStatus.OK).body(SUCCESS("登录成功", adminMap));
          }	    
	    }
	  
	  
	  @ApiOperation(value="注销登录", notes="注销登录")
		@ApiImplicitParams({
		})
	    @RequestMapping(value = "/outLogin",method = RequestMethod.POST)
	    @ResponseBody
	    public ResponseEntity<Map<String,Object>> outLogin(HttpServletRequest request,HttpServletResponse response){		
			  Map<String,String> data =RequestMapToUtil.getPostByTextPlain(request);	
			  //删除session
			   request.getSession().removeAttribute(Constant.SESSION_USER);
			   request.getSession().removeAttribute(Constant.SESSION_USER_ID);
			   request.getSession().removeAttribute(Constant.SESSION_NIKE_NAME);
		        //删除cookie
		       CookieUtil.removeCookie(request, response,Constant.COKKIES_USER_ID);			  
		      return ResponseEntity.status(HttpStatus.OK).body(SUCCESS("注销成功！",null)); 
	    }
	  
	  
	  
	  @ApiOperation(value="上传用户头像图片", notes="上传图片")
		@ApiImplicitParams({	
			@ApiImplicitParam(name = "attach", value = "图片", required = true, dataType = "File",paramType = "form"),			
			})
	    @RequestMapping(value = "/upLoadImg",method = RequestMethod.POST)
	    @ResponseBody
	    public ResponseEntity<Map<String,Object>> upLoadImg(HttpServletRequest request){			
			Map<String, Object> rs = null;
			 try {
			//attach 图片key	
			 rs =RequestMapToUtil.getPostByTextPlain(request,"attach");	
			} catch (Exception e) {				
				return ResponseEntity.status(HttpStatus.OK).body(SUCCESS("badFile",null)); 
			}	
			//数据集
			 Map<String,String> data =(Map<String,String>)rs.get("param");
		      //图片集
			 List<MultipartFile> fileList = (List<MultipartFile>) rs.get("fileList");
			 Map<String, String> fileRs = new HashMap<>();
			 if(fileList.size()!=1){
				 return ResponseEntity.status(HttpStatus.OK).body(ERROR("每次只能上传一张图片",null));
			 }
			 Map<String, Object> result = ImageUtil.uploadImageByOneBase(fileList.get(0), fileRs);
			 if(result.get("code")==SysCode.error){
		    		return ResponseEntity.status(HttpStatus.OK).body(ERROR(result.get("message"),null));
		    	 }
		    return ResponseEntity.status(HttpStatus.OK).body(SUCCESS("",result.get("data"))); 

	  }

		
}
